package DataStrucures;

import java.util.Arrays;

public class FindFindTheAlgorithm {
    public static void main(String[] args) {
        int[]arr={1,8,10,89,1000,1234};
        System.out.println(FibonacciGoldenSection(arr,89));
    }

    public static int BinaryLookup(int[] arr,int left,int right,int k){//二分查找递归实现
        int mid=(left+right)/2;
        if(arr[mid]==k)return mid;
        if(left>=right)return -1;
        if(arr[mid]>k)
            return BinaryLookup(arr,left,mid,k);
        else
            return BinaryLookup(arr,mid+1,right,k);
    }
    public static int BinarySearch(int[]arr ,int target){//二分查找非递归实现法
        int l=0;
        int r=arr.length-1;
        int mid;
        while (l<=r){
            mid=(l+r)/2;
            if(arr[mid]==target){
                return mid;
            }else if(arr[mid]<target){
                l=mid+1;
            }else {
                r=mid-1;
            }
        }
        return -1;
    }
    public static int InterpolateLookups(int[] arr,int left,int right,int k){//插值查找，对二分进行的优化
        int mid=left+(right-left)*(k-arr[left])/(arr[right]-arr[left]);//插值查找的精髓(自适应中间索引)
        if(arr[mid]==k)return mid;
        if(left>=right)return -1;
        if(arr[mid]>k)
            return InterpolateLookups(arr,left,mid,k);
        else
            return InterpolateLookups(arr,mid+1,right,k);
    }
    public static int[] fib(){
        int[]f=new int[20];
        f[0]=1;
        f[1]=1;
        for (int i = 2; i < 20; i++) {
            f[i]=f[i-1]+f[i-2];
        }
        return f;
    }
    public static int FibonacciGoldenSection(int[] arr,int key){//斐波那契黄金分割查找算法
        int low=0;
        int high=arr.length-1;
        int k=0;
        int mid=0;
        int f[]=fib();
        while (high>f[k]-1){
            k++;
        }
        int[]temp= Arrays.copyOf(arr,f[k]);
        for (int i = high+1; i < temp.length; i++) {
            temp[i]=arr[high];
        }while (low<=high){
            mid=low+f[k-1]-1;
            if(key<temp[mid]){
                high=mid-1;
                k--;
            }else if(key>temp[mid]){
                low=mid+1;
                k--;
                k--;
            }else {
                if(mid<=high){
                    return mid;
                }else return high;
            }
        }
        return -1;
    }
}
